import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
const { getTodayDate, getYesterdayDate, formatNumber, jump, getStorage } = require("../../utils/utils");
const app = getApp();

// pages/trophy/trophy.js
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		// 类型图片列表
		iconList: [
			// 学习
			"https://image-classify.daieco.com/kejian-space/V49nBESzwfPvfdc6a055c8ee133bb50947fd736436a8.png",
			// 厨余垃圾
			"https://image-classify.daieco.com/kejian-space/zna866jbDKkw266093b9bcd98f5f15aa5b6e44ad4c61.png",
			// 其他垃圾
			"https://image-classify.daieco.com/kejian-space/tqId1U1LRu2N97938b1969cdfeb707ef14f20e3b77be.png",
			// 有害垃圾
			"https://image-classify.daieco.com/kejian-space/KkTY9FwDUshQ15f9e3e518b6349d2b4b1c447019158e.png",
			// 可回收垃圾
			"https://image-classify.daieco.com/kejian-space/6RkmjUa2pLl76b668c7aadef51ba88fee1105a75ea35.png",
		],
		// 挑战数据
		data: {},
		// 昨天日期数据
		yesterdayDate: {
			...getYesterdayDate(),
		},
		// 今天日期数据
		todayDate: {
			...getTodayDate(),
		},
		// 选中日期数据
		date: {
			...getTodayDate(),
		},
		// 是否是今天
		isToday: true,
		// 完成日期列表
		doneList: [],
		// 未完成日期列表
		unDoneList: [],
		// 可补救日期列表
		remedyList: [],
		// 挑战子标题
		title: '',
		// 当前日期挑战状态
		taskStatus: null,
		// 用户挑战状态
		challengeStatus: null,
		// 补救次数
		helpNum: null,
		// 补救任务个数
		helpTaskNum: null,
		// 补救日期
		helpDate: null,
		// 挑战的第几天
		challengeDay: null,
		// 来自首页
		isFromIndex: false
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.setData({
			helpDate: options.date,
			isFromIndex: !!options?.date,
			date: getTodayDate(),
			todayDate: getTodayDate(),
		});
	},
	

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		this.modal = this.selectComponent('#modal')
		this.helpModal = this.selectComponent('#helpModal')
		this.calendar = this.selectComponent("#calendar");
		const { helpDate, isFromIndex } = this.data;
		if (this.calendar) {
			this.calendar.setSpot()
		}
		if (helpDate && isFromIndex) {
			const [year, month, day] = helpDate.split('-')
			this.calendar.selectChange({
				currentTarget: {
					dataset: {
						year: +year,
						month: +month,
						day: +day,
						dateString: helpDate,
					}
				},
			});
			this.calendar.openChange()
		} else {
			this.checkUserChallengeStatus()
		}
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.getStatus();
		this.getData();
		if (this.helpModal) {
			this.checkUserChallengeStatus()
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () { },

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () { },

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
		this.getData();
		this.getStatus();
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () { },

	// 判断用户是否挑战失败
	async checkUserChallengeStatus() {
		const res = await request.get(api.checkIsFail)
		if (res.httpStatus == 200) {
			if ([0, 3].includes(res.data?.status)) {
				this.setData({
					helpDate: res.data?.firstHelpDate,
					helpNum: res.data?.helpNum,
					helpTaskNum: res.data?.helpTaskNum,
					challengeStatus: res.data?.status,
				})
				this.helpModal.show()
			}
		}
	},
	//跳转挑战
	handleMedal() {
		this.setData({
			isFromIndex: false
		})
		wx.navigateTo({
			url: "/pages/example/example",
		});
	},
	/**
	 * 获取挑战数据
	 */
	async getData(date = {}) {
		this.getTitle({
			...this.data.date,
			...date,
		})
		const res = await request.get(api.challengeDetail, {
			...this.data.date,
			...date,
		});
		// 临时筛选知识点学习状态
		let hasStudy = getStorage('study')
		res?.data?.todayKonwledgeInfoDOS?.map((item)=>{
			if(hasStudy.search(item.taskSourceId)!=-1){
				item.completed = true
			}
		})
		this.setData({
			taskStatus: res?.data?.taskStatus,
			data: {
				percent: parseFloat(res?.data?.completePercent || 0),
				list: res?.data?.todayTaskInfoResps || [],
				learnList: res?.data?.todayKonwledgeInfoDOS || [],
			},
		});
		wx.stopPullDownRefresh();
	},
	/**
	 * 日期选中变化
	 * @param {*} e
	 */
	change(e) {
		const todayDate = getTodayDate();
		const date = {
			...e.detail,
		};
		date.year = date.year?.toString()
		date.month = formatNumber(date.month)
		date.day = formatNumber(date.day)
		this.setData({
			date,
			isToday:
				date.year === todayDate.year &&
				date.month === todayDate.month &&
				date.day === todayDate.day,
		});
		this.getData(date);
	},
	// 获取日历状态
	async getStatus() {
		const res = await request.get(api.challengeDate)
		const arr = res?.data || []

		const remedyList = arr.filter(f => (!f.completed && f.taskStatus === 1)).map(m => {
			return `${m.year}/${m.month}/${m.day}`
		})
		const unDoneList = arr.filter(f => !f.completed).map(m => {
			return `${m.year}/${m.month}/${m.day}`
		})
		const doneList = arr.filter(f => f.completed).map(m => {
			return `${m.year}/${m.month}/${m.day}`
		})

		this.setData({
			doneList,
			unDoneList,
			remedyList,
		})
		if (this.calendar) {
			this.calendar.setSpot()
		}
	},
	// 获取日历标题
	async getTitle({ dateString, ...date }) {
		if (!dateString) {
			dateString = `${date.year}-${date.month}-${date.day}`
		}
		const res = await request.get(api.challengeTitle, {
			taskTime: dateString + ' 00:00:00',
			...date
		})
		this.setData({
			challengeDay: res?.data?.days,
			title: (res?.data?.times && res?.data?.days)
				? `第${res.data.times}次挑战的第${res.data.days}天`
				: ''
		})
	},
	// 跳转到文章页面
	jumpArticle(e) {
		const {
			taskId,
			taskSourceId,
		} = e?.currentTarget?.dataset?.item || {}
		this.setData({
			isFromIndex: false
		})
		wx.navigateTo({
			url: `/pages/detail/detail?id=${taskSourceId}&taskId=${taskId}`
		})
	},
	/**
	 * 跳转拍照
	 * @param {*} e
	 */
	async jumpPhoto(e) {
		const {
			item: { completed, taskSourceId = "", taskId = "", taskType = "" },
		} = e.currentTarget?.dataset;
		const { taskStatus, isToday, challengeDay } = this.data;
		const isRemedy = taskStatus === 1 && !completed
		this.setData({
			isFromIndex: false
		})
		if (!completed && (isRemedy || isToday)) {
			if (taskType === 2) {
				jump('categoryPhoto', {
					...e.currentTarget?.dataset?.item,
					source: 3,
					challengeDay
				})
			} else {
				wx.navigateTo({
					url: `/pages/answer/answer?id=${taskSourceId}&taskId=${taskId}`,
				});
			}
		} else {
			if (taskType === 1) {
				if (completed) {
					wx.navigateTo({
						url: `/pages/result/result?id=${taskSourceId}&taskId=${taskId}`,
					});
				} else {
					wx.navigateTo({
						url: `/pages/detail/detail?id=${taskSourceId}&taskId=${taskId}`,
					});
				}
			}
		}
	},
	// 放弃挑战
	giveup() {
		this.modal.show()
	},
	// 放弃挑战提交
	async confirm(e) {
		const res = await request.get(api.challengeGiveup)
		if (res.httpStatus === 200) {
			e.detail?.hide()
			wx.showToast({
				title: '放弃成功',
			})
			jump('mine')
		}
	},
	// 去补救确认
	async helpConfirm(e) {
		const { challengeStatus, helpDate } = this.data;
		// 去补救
		if (challengeStatus == 0) {
			if (helpDate) {
				const [year, month, day] = helpDate.split('-')
				this.calendar.selectChange({
					currentTarget: {
						dataset: {
							year: +year,
							month: +month,
							day: +day,
							dateString: helpDate,
						}
					},
				});
				this.calendar.openChange()
			}
		}
		// 开启挑战
		if ([1, 4].includes(challengeStatus)) {
			await request.get(api.startChallenge, {});
			this.getUserData();
		}
		e.detail.hide?.()
	},
	// 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('default', e)
	},
});
